﻿using Microsoft.WindowsAzure.Storage.Blob;
using SpaceNeedle.City6473.Web.Data.Helpers;
using SpaceNeedle.City6473.Web.Data.Models;
using SpaceNeedle.City6473.Web.Data.Repositories;
using SpaceNeedle.City6473.WebSite.App_Start;
using SpaceNeedle.SDK.Cloud.Storage;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace SpaceNeedle.City6473.WebSite.Controllers
{
    [RoutePrefix("api/requestitems")]
    public class RequestItemsController : ApiController
    {
        private RequestItemRepository requestItemRepository = new RequestItemRepository();
        private RequestItemsSupportersRepository requestItemsSupportesRepository = new RequestItemsSupportersRepository();

        // GET api/<controller>
        public IEnumerable<RequestItem> Get()
        {
            return requestItemRepository.GetAllByDateDescendingWithUser();
        }

        public IEnumerable<RequestItem> Get(string user)
        {
            return requestItemRepository.GetAllByDateDescendingWithUserByUser(new Guid(user));
        }

        public IEnumerable<RequestItem> Get(int status)
        {
            return requestItemRepository.GetAllByDateDescending().Where(x => x.Status == status);
        }

        public RequestItem Get(Guid id)
        {
            return requestItemRepository.GetAllByDateDescending().Where(x => x.Id == id).SingleOrDefault();
        }

        [HttpGet]
        [Route("{requestItemId}/supporters")]
        public IEnumerable<Guid> GetSupporters(Guid requestItemId)
        {
            return requestItemsSupportesRepository.GetRequestItemSupporters(requestItemId);
        }

        [HttpGet]
        [Route("{requestItemId}/supporters/count")]
        public int GetSupportersCount(Guid requestItemId)
        {
            return requestItemsSupportesRepository.GetRequestItemSupportersCount(requestItemId);
        }

        [HttpGet]
        [Route("supportedby/{userId}")]
        public IEnumerable<RequestItem> GetSupportedRequestsByUser(Guid userId)
        {
            return requestItemsSupportesRepository.GetRequestItemsByUser(userId);
        }

        [HttpPost]
        [Route("{requestItemId}/supporters/add/{userId}")]
        public HttpStatusCode AddSupporter(Guid requestItemId, Guid userId)
        {
            try
            {
                requestItemsSupportesRepository.Insert(new RequestItemSupporter() { Id = Guid.NewGuid(), RequestItemId = requestItemId, CreatedBy = userId });
                return HttpStatusCode.OK;
            }
            catch { }

            return HttpStatusCode.InternalServerError;
        }

        [HttpPost]
        [Route("{requestItemId}/supporters/delete/{userId}")]
        public HttpStatusCode DeleteSupporter(Guid requestItemId, Guid userId)
        {
            try
            {
                requestItemsSupportesRepository.Delete(new RequestItemSupporter() { Id = Guid.NewGuid(), RequestItemId = requestItemId, CreatedBy = userId });

                return HttpStatusCode.OK;
            }
            catch { }

            return HttpStatusCode.InternalServerError;
        }

        

        public RequestItem Post([FromBody]RequestItem item, [FromUri]bool shareOnSocialNetwork)
        {
            item.CreationDate = DateTime.UtcNow;

            byte[] bytes = Convert.FromBase64String(item.Base64Photo);
            Image originalImage = Image.FromStream(new MemoryStream(bytes));

            var blobClient = AzureStorage.Account.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference("requests");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(item.Id + ".jpg");

            blockBlob.UploadFromByteArray(bytes, 0, bytes.Length);

            item.Photo = blockBlob.Uri.ToString();

            GenerateThumbnails(container, item, originalImage, bytes);

            //return blockBlob.Uri.ToString();

            bool wasCreated = false;

            do
            {
                item.Number = this.requestItemRepository.GetNextProtocolNumber();

                try
                {
                    requestItemRepository.Insert(item);
                    wasCreated = true;
                }
                catch { }

            } while (!wasCreated);

            if (shareOnSocialNetwork)
            {
                var user = new UserRepository().GetById(item.CreatedBy);

                if(user != null)
                {
                    if(user.provider == "Facebook")
                    {
                        var sucess = new AuthenticationController().SendPost(user, item.Id, item.Permalink);
                    }
                    else if(user.provider == "Twitter")
                    {
                        var sucess = new AuthenticationController().SendTweet(user, item.Id, item.Permalink);
                    }
                }
            }

            return item;
        }

        private void GenerateThumbnails(CloudBlobContainer container, RequestItem item, Image originalImage, byte[] bytes)
        {
            var blockBlob = container.GetBlockBlobReference(item.Id + "_260x180.jpg");
            Image thumbnail = ImageUtility.ResizeBitmap((Bitmap)ImageUtility.ByteArrayToImage(bytes), 260, 180, SpaceNeedle.City6473.WebSite.App_Start.ImageUtility.PicturePosition.Fill);
            bytes = ImageUtility.ImageToByteArray(thumbnail);
            blockBlob.UploadFromByteArray(bytes, 0, bytes.Length);

            bytes = Convert.FromBase64String(item.Base64Photo);
            blockBlob = container.GetBlockBlobReference(item.Id + "_612.jpg");

            int w = 612;
            int h = 612;

            if (w > originalImage.Width)
            {
                w = originalImage.Width;
            }

            if (h > originalImage.Height)
            {
                h = originalImage.Height;
            }
            thumbnail = ImageUtility.ResizeBitmap((Bitmap)ImageUtility.ByteArrayToImage(bytes), w, h, SpaceNeedle.City6473.WebSite.App_Start.ImageUtility.PicturePosition.Fill);
            bytes = ImageUtility.ImageToByteArray(thumbnail);
            blockBlob.UploadFromByteArray(bytes, 0, bytes.Length);
        }

        private Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        private byte[] GetBase64StringBytes(string base64String)
        {
            //Bitmap bmpReturn = null;

            return Convert.FromBase64String(base64String);

            /*
            MemoryStream memoryStream = new MemoryStream(byteBuffer);

            memoryStream.Position = 0;

            bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);

            memoryStream.Close();
            memoryStream = null;
            byteBuffer = null;

            return bmpReturn;*/
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {

        }

        public bool SetStatus(Guid id, int status, string statusInfo, Guid adminId)
        {
            try
            {
                var item = requestItemRepository.GetById(id);

                if (item != null)
                {
                    item.Status = status;
                    item.StatusInfo = statusInfo;
                    item.UpdateDate = DateTime.UtcNow;
                    item.UpdatedBy = adminId;

                    requestItemRepository.Update(item);

                    WebSiteContent staticContent = new WebSiteContent();
                    string message = staticContent.RequestItems.StatusChangedToastMessage;

                    if (item.Status == 2) //Fechado Com Solução
                    {
                        message = staticContent.RequestItems.StatusSolvedToastMessage;                       
                    }
                    else if (item.Status == 3) //Fechado Sem Solução
                    {
                        message = staticContent.RequestItems.StatusClosedToastMessage;
                    }

                    new UserDeviceRepository().NotifyByUser(item.CreatedBy, "", message, "/Views/RequestItemDetails.xaml?requestItemId=" + item.Id.ToString());

                    //PushNotifications.SendWp8ToastNofitication("6473", "Solicitacao Atualizada", "/Views/RequestItemDetails.xaml?requestItemId=" + item.Id.ToString(), "http://sn1.notify.live.net/throttledthirdparty/01.00/AQHlIcNx00apRrR9rsi6CQtpAgAAAAADAQAAAAQUZm52OkJCMjg1QTg1QkZDMkUxREQFBlVTU0MwMQ");
                    return true;
                }
            }
            catch { }

            return false;
        }
        // DELETE api/<controller>/5
        public bool Delete(Guid id)
        {
            try
            {
                var item = requestItemRepository.GetById(id);

                if (item != null)
                {
                    requestItemRepository.Delete(item);

                    var blobClient = AzureStorage.Account.CreateCloudBlobClient();

                    CloudBlobContainer container = blobClient.GetContainerReference("requests");

                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(id + ".jpg");

                    try
                    {
                        blockBlob.Delete();
                    }
                    catch { }

                    try
                    {
                        blockBlob = container.GetBlockBlobReference(id + "_260x180.jpg");
                        blockBlob.Delete();
                    }
                    catch { }

                    try
                    {
                        blockBlob = container.GetBlockBlobReference(id + "_612.jpg");
                        blockBlob.Delete();
                    }
                    catch { }

                    return true;
                }
            }
            catch { }

            return false;
        }
    }
}